/*
 *所有关于Layered_Process_Audit类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*Layered_Process_AuditService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using DGZImp.Core.BaseProvider;
using DGZImp.Core.Extensions.AutofacManager;
using ATkg.BizAppProject.DomainModels;
using System.Linq;
using DGZImp.Core.Utilities;
using System.Linq.Expressions;
using DGZImp.Core.Extensions;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using ATkg.BizAppProject.IRepositories;
using DGZImp.Core.DbSqlSugar;
using static ATkg.BizAppProject.Controllers.Layered_Process_AuditController;
using System.Text.Json;
using System.Configuration;
using Microsoft.Extensions.Configuration;
using System.Net.Http;

namespace ATkg.BizAppProject.Services
{

    public partial class Layered_Process_AuditService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ILayered_Process_AuditRepository _repository;//访问数据库
        private readonly string _connectionString; // 存储连接字符串

        [ActivatorUtilitiesConstructor]
        public Layered_Process_AuditService(
            ILayered_Process_AuditRepository dbRepository,
            IHttpContextAccessor httpContextAccessor,
            IConfiguration configuration // 注入配置服务

            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
            // 在构造函数中获取连接字符串
            // 方法1：直接通过配置路径获取（推荐）
            _connectionString = configuration["DBSettings:Connection:ServiceDbContext"];
            

            // 方法2：如果方法1失败，尝试获取整个Connection节点再取值
            if (string.IsNullOrEmpty(_connectionString))
            {
                var connectionSection = configuration.GetSection("Connection");
                _connectionString = connectionSection["ServiceDbContext"];
            }

            // 方法3：作为最后的备选，打印所有配置项用于调试
            if (string.IsNullOrEmpty(_connectionString))
            {
                var allConfig = configuration.AsEnumerable().ToList();
                var configLog = string.Join("\n", allConfig.Select(c => $"{c.Key}: {c.Value}"));
                throw new ArgumentNullException(nameof(_connectionString),
                    $"无法读取 Connection:ServiceDbContext！\n当前配置项：\n{configLog}");
            }


        }
        // 将网页中填写的审核信息传入数据库
        public async Task<object> DealDataFromWeb(AuditSubmitModel model)
        {

            var checkItemsJson = JsonSerializer.Serialize(model.CheckResults, new JsonSerializerOptions
            {
                WriteIndented = true, // 格式化JSON，便于阅读
                Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            });

            var auditRecord = new Layered_Process_Audit
            {

                LevelLabel = (string)model.LevelLabel,  // 替换为实际的字段名和值
                ProductionLine = (string)model.ProductionLine,  // 替换为实际的字段名和值
                ResponsiblePerson = (string)model.ResponsiblePerson,  // 替换为实际的字段名和值
                FinalResult = (string)model.FinalResult,  // 替换为实际的字段名和值
                CheckResults = checkItemsJson,
            };
            await Db.DoInsertAsync<Layered_Process_Audit>(auditRecord);

            var Data = await Db.Set<Layered_Process_Audit>()
                    .Where(x => x.IsValid == 1) // 汇总表按 ProductId 唯一分组，此条件可定位单条
                    .FirstOrDefaultAsync();
            return Data == null ? "暂无数据" : Data.CreateTime.ToString();
        }
        // 获取数据库中  审核总次数、今日审核、待整改项、已完成整改  这4个数在主页面中进行展示
        public async Task<object> GetDataFromDB(SearchContet model)
        {
            try
            {
                // 获取前端传入的查询参数
                var levelLabel = model.LevelLabel?.ToString();
                if (!int.TryParse(model.year.ToString(), out int year) ||
                    !int.TryParse(model.month.ToString(), out int month))
                {
                    throw new ArgumentException("无效的年份或月份参数");
                }

                // 计算指定年月的第一天和最后一天（精确到时间）
                var firstDayOfMonth = new DateTime(year, month, 1);
                var lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);
                var startOfMonth = firstDayOfMonth;
                var endOfMonth = lastDayOfMonth.AddDays(1).AddTicks(-1); // 当月最后一刻

                // 计算今天的范围（用于今日审核数）
                var today = DateTime.Today;
                var isTodayInTargetMonth = today.Year == year && today.Month == month;
                var startOfToday = today;
                var endOfToday = today.AddDays(1).AddTicks(-1);

                // 并行执行查询，但使用独立的数据库上下文
                //var totalAuditsTask = Task.Run(async () =>
                //{
                //    using (var db = GetNewDbInstance())
                //    {
                //        return await db.Set<Layered_Process_Audit>()
                //            .Where(x => x.IsValid == 1
                //                && x.CreateTime >= startOfMonth
                //                && x.CreateTime <= endOfMonth
                //                && (string.IsNullOrEmpty(levelLabel) || x.LevelLabel == levelLabel))
                //            .CountAsync();
                //    }
                //});
                // 获取所选年月NG总数量，不以审核级别划分
                var ngCountTask = Task.Run(async () =>
                {
                    using (var db = GetNewDbInstance())
                    {
                        return await db.Set<Layered_Process_Audit>()
                            .Where(x => x.IsValid == 1
                                && x.FinalResult == "N"
                                && x.CreateTime >= startOfMonth
                                && x.CreateTime <= endOfMonth
                                //&& (string.IsNullOrEmpty(levelLabel) || x.LevelLabel == levelLabel)
                                )
                            .CountAsync();
                    }
                });
                // 获取所选年月Corrected总数量，不以审核级别划分
                var correctedCountTask = Task.Run(async () =>
                {
                    using (var db = GetNewDbInstance())
                    {
                        return await db.Set<Layered_Process_Audit>()
                            .Where(x => x.IsValid == 1
                                && x.FinalResult == "C"
                                && x.CreateTime >= startOfMonth
                                && x.CreateTime <= endOfMonth
                                //&& (string.IsNullOrEmpty(levelLabel) || x.LevelLabel == levelLabel)
                                )
                            .CountAsync();
                    }
                });

                //var todayCountTask = Task.Run(async () =>
                //{
                //    // 只有当查询的是当前月份时，才统计今日数据
                //    if (!isTodayInTargetMonth) return 0;

                //    using (var db = GetNewDbInstance())
                //    {
                //        return await db.Set<Layered_Process_Audit>()
                //            .Where(x => x.IsValid == 1
                //                && x.CreateTime >= startOfToday
                //                && x.CreateTime <= endOfToday
                //                && (string.IsNullOrEmpty(levelLabel) || x.LevelLabel == levelLabel))
                //            .CountAsync();
                //    }
                //});

                // 获取当月符合条件的所有审核项目详细信息
                var monthlyAuditsTask = Task.Run(async () =>
                {
                    using (var db = GetNewDbInstance())
                    {
                        return await db.Set<Layered_Process_Audit>()
                            .Where(x => x.IsValid == 1
                                && x.CreateTime >= startOfMonth
                                && x.CreateTime <= endOfMonth
                                && (string.IsNullOrEmpty(levelLabel) || x.LevelLabel == levelLabel))
                            .Select(x => new
                            {
                                ProductionLine = x.ProductionLine,
                                LevelLabel = x.LevelLabel,
                                FinalResult = x.FinalResult,
                                CreateTime = x.CreateTime,
                                ModifyTime = x.ModifyTime
                            })
                            .OrderByDescending(x => x.CreateTime)
                            .ToListAsync();
                    }
                });

                // 等待所有查询完成
                //await Task.WhenAll(totalAuditsTask, ngCountTask, correctedCountTask, todayCountTask, monthlyAuditsTask);
                await Task.WhenAll( ngCountTask, correctedCountTask, monthlyAuditsTask);

                // 返回结果
                return new
                {
                    //TotalAudits = await totalAuditsTask,
                    NgCount = await ngCountTask,
                    CorrectedCount = await correctedCountTask,
                    //TodayAudits = await todayCountTask,
                    MonthlyAudits = await monthlyAuditsTask,
                };
            }
            catch (Exception ex)
            {
                // 记录错误日志
                // _logger.LogError(ex, "获取统计数据失败");
                throw new Exception("获取统计数据失败: " + ex.Message);
            }
        }

        // 获取数据库中所有NG(待整改)的信息，返回主要信息进行简要展示，在待整改页面中进行展示
        public async Task<object> GetNgResultsData([FromBody] SearchContet model)
        {
            try
            {
                if (!int.TryParse(model.year.ToString(), out int year) ||
                    !int.TryParse(model.month.ToString(), out int month))
                {
                    throw new ArgumentException("无效的年份或月份参数");
                }

                // 计算指定年月的第一天和最后一天（精确到时间）
                var firstDayOfMonth = new DateTime(year, month, 1);
                var lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);
                var startOfMonth = firstDayOfMonth;
                var endOfMonth = lastDayOfMonth.AddDays(1).AddTicks(-1); // 当月最后一刻
                // 使用独立的数据库实例查询所有FinalResult为N的记录
                using (var db = GetNewDbInstance())
                {
                    // 查询所有有效且FinalResult为N的记录
                    var nResults = await db.Set<Layered_Process_Audit>()
                        .Where(x => x.IsValid == 1 && x.FinalResult == "N" && x.CreateTime >= startOfMonth
                                && x.CreateTime <= endOfMonth)
                        .OrderByDescending(x => x.CreateTime) // 按创建时间倒序，最新的在前
                        .ToListAsync();

                    // 如果需要分页，可以添加Skip和Take
                    // 例如：.Skip((pageIndex - 1) * pageSize).Take(pageSize)

                    // 返回结果和总条数
                    return new
                    {
                        TotalCount = nResults.Count,
                        Data = nResults.Select(item => new
                        {
                            // 只返回需要的字段，避免暴露过多信息
                            CreateTime = item.CreateTime, // 审核时间
                            Id = item.Id,
                            ResponsiblePerson = item.ResponsiblePerson, //审核人
                            ProductionLine = item.ProductionLine, //工段
                            LevelLabel = item.LevelLabel, // 审核级别
                            FinalResult = item.FinalResult, // 审核结果
                            CheckResults = item.CheckResults, // 审核项详细信息

                        }).ToList()
                    };
                }
            }
            catch (Exception ex)
            {
                // 错误处理
                throw new Exception("获取待整改记录失败: " + ex.Message);
            }
        }
        // 获取数据库中所有Corrected(已整改)的信息，返回主要信息进行简要展示，在已整改页面中进行展示
        public async Task<object> GetCorrectedResultsData([FromBody] SearchContet model)
        {
            try
            {

                if (!int.TryParse(model.year.ToString(), out int year) ||
                    !int.TryParse(model.month.ToString(), out int month))
                {
                    throw new ArgumentException("无效的年份或月份参数");
                }

                // 计算指定年月的第一天和最后一天（精确到时间）
                var firstDayOfMonth = new DateTime(year, month, 1);
                var lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);
                var startOfMonth = firstDayOfMonth;
                var endOfMonth = lastDayOfMonth.AddDays(1).AddTicks(-1); // 当月最后一刻
                // 使用独立的数据库实例查询所有FinalResult为N的记录
                using (var db = GetNewDbInstance())
                {
                    // 查询所有有效且FinalResult为N的记录
                    var nResults = await db.Set<Layered_Process_Audit>()
                        .Where(x => x.IsValid == 1 && x.FinalResult == "C" && x.CreateTime >= startOfMonth
                                && x.CreateTime <= endOfMonth)
                        .OrderByDescending(x => x.CreateTime) // 按创建时间倒序，最新的在前
                        .ToListAsync();

                    // 如果需要分页，可以添加Skip和Take
                    // 例如：.Skip((pageIndex - 1) * pageSize).Take(pageSize)

                    // 返回结果和总条数
                    return new
                    {
                        TotalCount = nResults.Count,
                        Data = nResults.Select(item => new
                        {
                            // 只返回需要的字段，避免暴露过多信息
                            CreateTime = item.CreateTime, // 审核时间
                            Id = item.Id,
                            ResponsiblePerson = item.ResponsiblePerson, //审核人
                            ProductionLine = item.ProductionLine, //工段
                            LevelLabel = item.LevelLabel, // 审核级别
                            FinalResult = item.FinalResult, // 审核结果
                            CheckResults = item.CheckResults, // 审核项详细信息

                        }).ToList()
                    };
                }
            }
            catch (Exception ex)
            {
                // 错误处理
                throw new Exception("获取待整改记录失败: " + ex.Message);
            }
        }
        public async Task<object> DealCorrectedDataFromWeb(AuditCorrectedModel model )
        {
            try
            {
                var checkItemsJson = JsonSerializer.Serialize(model.CheckResults, new JsonSerializerOptions
                {
                    WriteIndented = true, // 格式化JSON，便于阅读
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                });
                // 根据前端传入的ID查询对应的记录
                var existingRecord = await Db.Set<Layered_Process_Audit>()
                    .Where(x => x.Id == model.Id && x.IsValid == 1)
                    .FirstOrDefaultAsync();

                // 如果记录不存在
                if (existingRecord == null)
                {
                    return ($"未找到ID为{model.Id}的审核记录");
                }
                // 更新需要修改的字段
                existingRecord.CheckResults = checkItemsJson;
                existingRecord.FinalResult = model.FinalResult;

                // 执行更新操作
                await Db.DoUpdateAsync<Layered_Process_Audit>(existingRecord);

                // 查询更新后的记录并返回
                var updatedRecord = await Db.Set<Layered_Process_Audit>()
                    .Where(x => x.Id == model.Id && x.IsValid == 1)
                    .FirstOrDefaultAsync();
                return updatedRecord == null ? "暂无数据" : updatedRecord.ModifyTime.ToString();
            }
            catch (Exception ex)
            {
                // 错误处理
                throw new Exception("获取待整改记录失败: " + ex.Message);
            }
        }

        public async Task<object> GetInfoFromDbPeopleManage()
        {
            try
            {
                using (var db = GetNewDbInstance())
                {
                    // 查询所有有效且FinalResult为N的记录
                    var nResults = await db.Set<Lpa_People_Manage>()
                        .Where(x => x.IsValid == 1)
                        .OrderByDescending(x => x.CreateTime) // 按创建时间倒序，最新的在前
                        .ToListAsync();

                    // 返回结果和总条数
                    return new
                    {
                        TotalCount = nResults.Count,
                        Data = nResults.Select(item => new
                        {
                            ProductionLine = item.ProductionLine, //工段
                            Chief = item.Chief, //工段长/主管
                            Minister = item.Minister, //车间主任/（副）部长
                            GeneralManager = item.GeneralManager, //分管（副）总 
                        }).ToList()
                    };
                }
            }
            catch (Exception ex)
            {
                // 错误处理
                throw new Exception("获取待整改记录失败: " + ex.Message);
            }
        }

        // 辅助方法：创建新的数据库实例（确保线程安全）
        private SqlSugarClient GetNewDbInstance()
        {
            // 根据你的实际配置创建新的SqlSugarClient实例
            return new SqlSugarClient(new ConnectionConfig
            {
                ConnectionString = _connectionString,
                DbType = DbType.MySql, // 或对应的数据库类型
                IsAutoCloseConnection = true, // 自动关闭连接
                InitKeyType = InitKeyType.Attribute
            });
        }

    }
}

